# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 16:06:07 2021

@author: Think
"""
"""
NFV敏感性分析
"""
import os

import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as optimize
import xlrd
from xlutils.copy import copy

import AppAvaCal
import LDH

# excel的存放路径
excel_path = r'C:\Users\小贱\Desktop\大论文文件夹\NFV敏感性分析\程序\程序\file.xls'


class ExcelUpdate(object):
    def __init__(self):
        self.old_input_excel = xlrd.open_workbook(excel_path)
        self.new_input_excel = copy(self.old_input_excel)

    def update_value(self, cell, value, sheet_name):
        '''
        - cell:传入一个单元格坐标参数，例如：cell=(0,0),表示修改第一行第一列

        '''
        sheet = self.new_input_excel.get_sheet(sheet_name)
        sheet.write(*cell, value)
        os.remove(excel_path)
        self.new_input_excel.save(excel_path)

    def update_values(self, cells, values, sheet_name):
        '''
        - cells:传入一个单元格坐标参数的list
        - values:传入一个修改值的list，
        例如：cells = [(0,0),(0,1)], values = [('a','b')]
        表示将列表第一行第一列和第一行第二列，分别修改为a 和 b 
        '''
        for i in range(len(cells)):
            self.update_value(cells[i], values[i], sheet_name)


def target_func(x, a0, a1, a2):
    return a0 * np.exp(-x / a1) + a2


def ex_nihe(x, a):
    a0 = max(a) - min(a)
    a1 = x[round(len(x) / 2)]
    a2 = min(a)
    p0 = [a0, a1, a2]
    para, cov = optimize.curve_fit(target_func, x, a, p0=p0)
    y_fit = [target_func(a, *para) for a in x]
    return y_fit


# 主效应图分析-正确性分析


if __name__ == '__main__':
    start = ExcelUpdate()
    file = os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep + ".") \
           + os.sep + '程序' + os.sep + "file.xls"
    D = 3  # 参数变量的个数
    N = 20  # 采样的个数
    bounds = [[10, 100], [10, 100],
              [0, 1]]  # 参数的取值范围
    samples_a = LDH.LHSample(D, bounds, N)
    start = ExcelUpdate()
    cells1 = [(1, 2), (3, 2),
              (3, 4)]  # 节点故障检测率
    # 节点平均人工维修时间
    # cells2=[]#倒换时间
    # for i in range(29):
    #     for j in range(3):
    #         cells2.append((5*i+j+3,6))#主备倒换时间
    # cells2 = [(1,6),(2,6)]#主备倒换时间

    All_App1_avail = []
    All_App2_avail = []
    App1_avail = []
    App2_avail = []
    for i in range(100):
        cell = (1, 4)  # DCGW节点MTBF
        value = 0.01 * (i + 1)
        # value = (0.01*i)
        start.update_value(cell, value, 'fail_info')
        for j in range(len(samples_a)):
            values1 = ['%f年' % samples_a[j][0], '%f年' % samples_a[j][1], samples_a[j][2]]
            start.update_values(cells1, values1, 'fail_info')
            single_app_avail, whole_app_avail = AppAvaCal.app_ava_cal(file, T=200, N=10, MT_time=10)
            App1_avail.append(single_app_avail['result'][0])
            App2_avail.append(single_app_avail['result'][1])
        All_App1_avail.append(np.mean(App1_avail))
        All_App2_avail.append(np.mean(App2_avail))

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文显示
    plt.rcParams['axes.unicode_minus'] = False  # 解决符号无法显示
    x = np.arange(0, 1, 0.01)

    # 设置图标标题，并给坐标轴加上标签
    # plt.title("链路重要度",fontsize=24)
    plt.xlabel("DCGW节点故障检测率", fontsize=14)
    plt.ylabel("业务可用度", fontsize=14)

    # y1_fit = ex_nihe(x, All_App1_avail)
    # y2_fit = ex_nihe(x, All_App2_avail)
    # plt.plot(x,y1_fit,'g',label = "App1拟合" )
    # plt.plot(x,y2_fit,'r',label = "App2拟合" )

    plt.plot(x, All_App1_avail, linewidth=1, label='App1')
    plt.plot(x, All_App2_avail, linewidth=1, label='App2')
    plt.legend()

    plt.show()

'''
#全效应指数计算

if __name__ == '__main__':
    file = os.path.abspath(os.path.dirname(os.getcwd())+os.path.sep+".")\
            +os.sep+'程序'+os.sep+"file.xls"
    D = 26 #参数变量的个数
    N = 5 #采样的个数
    bounds = [[10,100],[10,100],[10,100],[1,5],[1,5],
              [0,1],[0,1],[0,1],[0,1],[0,1],
              [10,100],[10,100],[10,100],[100,500],[100,500],
              [0,1],[0,1],
              [2,20],[2,20],
              [1,10],[1,10],[1,10],[1,10],[1,10],              
              [10,100],[0.1,0.5]]#参数的取值范围
    samples_a = LDH.LHSample(D,bounds,N)
    samples_b = LDH.LHSample(D,bounds,N)
    whole_app_avail = []
    all_avail_result_a = []
    all_avail_result_b = []
    start = ExcelUpdate()
    cells1 = [(1,2),(3,2),(4,2),(5,2),(6,2),#VM节点MTBF
              (1,4),(3,4),(4,4),(5,4),(6,4),#节点故障检测率
              (1,5),(3,5),(4,5),(5,5),(6,5),#节点故障检测时间 
              (5,6),(6,6),#节点自动维修概率
              (5,7),(6,7),#节点自动维修时间
              (1,8),(3,8),(4,8),(5,8),(6,8)]#节点平均人工维修时间
    #cells2=[]#倒换时间
    # for i in range(29):
    #     for j in range(3):
    #         cells2.append((5*i+j+3,6))#主备倒换时间
    cells2 = [(1,6),(2,6)]#主备倒换时间
    
    
    for i in range(len(samples_a)):
                
        values1 = ['%f年'%samples_a[i][0],'%f年'%samples_a[i][1],'%f年'%samples_a[i][2],'%f年'%samples_a[i][3],'%f年'%samples_a[i][4],
                    samples_a[i][5],samples_a[i][6],samples_a[i][7],samples_a[i][8],samples_a[i][9],
                    '%fs'%samples_a[i][10],'%fs'%samples_a[i][11],'%fs'%samples_a[i][12],'%fs'%samples_a[i][13],'%fs'%samples_a[i][14],
                    samples_a[i][15],samples_a[i][16],
                    '%fmin'%samples_a[i][17],'%fmin'%samples_a[i][18],
                    '%fh'%samples_a[i][19],'%fh'%samples_a[i][20],'%fh'%samples_a[i][21],'%fh'%samples_a[i][22],'%fh'%samples_a[i][23]]    
        values2 = ['%fs'%samples_a[i][24],'%fs'%samples_a[i][24] ]
        # values2 = ['%fs'%samples_a[i][13]]*2
        start.update_values(cells1, values1, 'fail_info')
        start.update_values(cells2, values2, 'VNF_info')
        single_app_avail, app_avail = AppAvaCal.app_ava_cal(file, t_period=200, N=100, MT_time=samples_a[i][25])
        whole_app_avail.append(app_avail)
    all_avail_result_a.append(whole_app_avail)
    
    
    for j in range(D):
        whole_app_avail = []
        a = np.array( samples_a, copy = True)
        b = np.array( samples_b, copy = True)
        a[:,j] = b[:,j]
        for i in range(len(a)):
                values1 = ['%f年'%a[i][0],'%f年'%a[i][1],'%f年'%a[i][2],'%f年'%a[i][3],'%f年'%a[i][4],
                    a[i][5],a[i][6],a[i][7],a[i][8],a[i][9],
                    '%fs'%a[i][10],'%fs'%a[i][11],'%fs'%a[i][12],'%fs'%a[i][13],'%fs'%a[i][14],
                    a[i][15],a[i][16],
                    '%fmin'%a[i][17],'%fmin'%a[i][18],
                    '%fh'%a[i][19],'%fh'%a[i][20],'%fh'%a[i][21],'%fh'%a[i][22],'%fh'%a[i][23]]    
                values2 = ['%fs'%a[i][24],'%fs'%a[i][24] ]
                # values2 = ['%fs'%samples_a[i][13]]*2
                start.update_values(cells1, values1, 'fail_info')
                start.update_values(cells2, values2, 'VNF_info')
                single_app_avail, app_avail = AppAvaCal.app_ava_cal(file, t_period=500, N=100, MT_time=a[i][25])
                whole_app_avail.append(app_avail)
        all_avail_result_a.append(whole_app_avail)
    

    whole_app_avail = []
    for i in range(len(samples_b)):
        values1 = ['%f年'%samples_b[i][0],'%f年'%samples_b[i][1],'%f年'%samples_b[i][2],'%f年'%samples_b[i][3],'%f年'%samples_b[i][4],
                    samples_b[i][5],samples_b[i][6],samples_b[i][7],samples_b[i][8],samples_b[i][9],
                    '%fs'%samples_b[i][10],'%fs'%samples_b[i][11],'%fs'%samples_b[i][12],'%fs'%samples_b[i][13],'%fs'%samples_b[i][14],
                    samples_b[i][15],samples_b[i][16],
                    '%fmin'%samples_b[i][17],'%fmin'%samples_b[i][18],
                    '%fh'%samples_b[i][19],'%fh'%samples_b[i][20],'%fh'%samples_b[i][21],'%fh'%samples_b[i][22],'%fh'%samples_b[i][23]]    
        values2 = ['%fs'%samples_b[i][24],'%fs'%samples_b[i][24] ]
        # values2 = ['%fs'%samples_a[i][13]]*2
        start.update_values(cells1, values1, 'fail_info')
        start.update_values(cells2, values2, 'VNF_info')
        single_app_avail, app_avail = AppAvaCal.app_ava_cal(file, t_period=500, N=100, MT_time=samples_b[i][25])
        whole_app_avail.append(app_avail)
    all_avail_result_b.append(whole_app_avail)
    
    
    for j in range(D):
        whole_app_avail = []
        a = np.array( samples_a, copy = True)
        b = np.array( samples_b, copy = True)
        b[:,j] = a[:,j]
        for i in range(len(b)):         
                values1 = ['%f年'%b[i][0],'%f年'%b[i][1],'%f年'%b[i][2],'%f年'%b[i][3],'%f年'%b[i][4],
                    b[i][5],b[i][6],b[i][7],b[i][8],b[i][9],
                    '%fs'%b[i][10],'%fs'%b[i][11],'%fs'%b[i][12],'%fs'%b[i][13],'%fs'%b[i][14],
                    b[i][15],b[i][16],
                    '%fmin'%b[i][17],'%fmin'%b[i][18],
                    '%fh'%b[i][19],'%fh'%b[i][20],'%fh'%b[i][21],'%fh'%b[i][22],'%fh'%b[i][23]]    
                values2 = ['%fs'%b[i][24],'%fs'%b[i][24] ]
                # values2 = ['%fs'%samples_a[i][13]]*2
                start.update_values(cells1, values1, 'fail_info')
                start.update_values(cells2, values2, 'VNF_info')
                single_app_avail, app_avail = AppAvaCal.app_ava_cal(file, t_period=200, N=10, MT_time=b[i][25])
                whole_app_avail.append(app_avail)
        all_avail_result_b.append(whole_app_avail)
        
        
    sin_index_1 = []
    sin_index_2 = []
    for i in range(1,len(all_avail_result_a)):
        y1 = all_avail_result_a[0]
        y2 = all_avail_result_b[0]
        c1 = all_avail_result_a[i]
        c2 = all_avail_result_b[i]
        v1= np.var(y1+y2)
        e1= np.dot((np.array(y1)-np.array(c1)),(np.array(y1)-np.array(c1)))/(2*N)
        s1=e1/v1
        sin_index_1.append(s1)
        e2= np.dot((np.array(y2)-np.array(c2)),(np.array(y2)-np.array(c2)))/(2*N)
        s2 = e2/v1
        sin_index_2.append(s2)
    print("全效应指数为：",sin_index_1)
    print("全效应2指数为：",sin_index_2)        
'''
